package com.dongdongshop.service.impl;

import com.alibaba.fastjson.JSON;
import com.dongdongshop.mapper.TbSpecificationMapper;
import com.dongdongshop.mapper.TbSpecificationOptionMapper;
import com.dongdongshop.mapper.TbTypeTemplateMapper;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.TypeTemplateService;
import com.dongdongshop.vo.SpecVo;
import com.dongdongshop.vo.TypeTemplateVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.dc.pr.PRError;

import java.util.List;

@DubboService
@Service
public class TypeTemplateServiceImpl implements TypeTemplateService {
    @Autowired
    private TbTypeTemplateMapper tbTypeTemplateMapper;

    @Autowired
    private TbSpecificationMapper tbSpecificationMapper;
    
    @Autowired
    private TbSpecificationOptionMapper tbSpecificationOptionMapper;
    
    @Override
    public List<TbTypeTemplate> listTemplate() {
        return tbTypeTemplateMapper.selectByExample(null);
    }

    @Override
    public void delTemplates(List<Long> ids) {
        TbTypeTemplateExample example = new TbTypeTemplateExample();
        TbTypeTemplateExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(ids);
        tbTypeTemplateMapper.deleteByExample(example);
        
    }

    @Override
    public void addTemplate(TbTypeTemplate tbTypeTemplate) {
        tbTypeTemplateMapper.insertSelective(tbTypeTemplate);
    }

    @Override
    public TbTypeTemplate toUpdate(Long id) {
        return tbTypeTemplateMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateTemplate(TbTypeTemplate tbTypeTemplate) {
        tbTypeTemplateMapper.updateByPrimaryKeySelective(tbTypeTemplate);
    }

    @Override
    public TypeTemplateVo getTypeTemplateVoById(Long id) {
        TypeTemplateVo typeTemplateVo = new TypeTemplateVo();
        TbTypeTemplate tbTypeTemplate = tbTypeTemplateMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(tbTypeTemplate,typeTemplateVo);

        String specIds = tbTypeTemplate.getSpecIds();
        List<SpecVo> specVos = JSON.parseArray(specIds, SpecVo.class);
        specVos.forEach(specVo ->{
            TbSpecificationOptionExample example = new TbSpecificationOptionExample();
            TbSpecificationOptionExample.Criteria criteria = example.createCriteria();
            criteria.andSpecIdEqualTo(specVo.getId());
            List<TbSpecificationOption> tbSpecificationOptions = tbSpecificationOptionMapper.selectByExample(example);
            specVo.setSpecOptionList(tbSpecificationOptions);
        });
        typeTemplateVo.setSpecVoList(specVos);
        return typeTemplateVo;
    }
}
